package org.gd.hellojson.gson;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class GsonJsonSerializer implements JsonDeserializer<Date>, JsonSerializer<Date> {

    private SimpleDateFormat dateFormat;

    public GsonJsonSerializer() {
    }

    public GsonJsonSerializer(String dateFormat, Locale locale) {
        this();
        this.dateFormat = new SimpleDateFormat(dateFormat, locale);
    }

    @Override
    public JsonElement serialize(Date date, Type typeOfSrc, JsonSerializationContext context) {
        String dateFormatAsString = dateFormat.format(date);
        return new JsonPrimitive(dateFormatAsString);
    }

    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        try {
            return dateFormat.parse(json.getAsString());
        } catch (ParseException e) {
            throw new JsonSyntaxException(json.getAsString(), e);
        }
    }
}
